package cn.alone.pet.controller;
import cn.alone.basic.BusinessException;
import cn.alone.basic.util.AjaxResult;
import cn.alone.basic.util.LoginContext;
import cn.alone.basic.util.PageList;
import cn.alone.pet.domain.Pet;
import cn.alone.pet.query.PetQuery;
import cn.alone.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;


    /**
     * 通过id获取一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Pet findById(@PathVariable("id") Long id){
        return petService.loadByIdDetail(id);
    }

    /**
     * 领养宠物
     * @param id
     * id=被领养宠物id
     * @param request
     * request=领养人信息
     * @return
     */
    @GetMapping("/adopt/{id}")
    public AjaxResult adopt(@PathVariable("id") Long id, HttpServletRequest request){
        try {
            petService.adopt(id, LoginContext.getCurrentLogininfo(request));
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("领养操作异常,请联系管理员");
        }
    }

    /**
     * 在售宠物
     * @param ids
     * ids=被勾选宠物的id
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids){
        try {
            petService.onSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("领养操作异常,请联系管理员");
        }

    }

    /**
     * 下架宠物
     * @param ids
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            petService.offSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("领养操作异常,请联系管理员");
        }

    }

    /**
     * 分页加高级查询
     * @param query
     * @return
     */
    @PostMapping
    public PageList<Pet> queryPage(@RequestBody PetQuery query){

        return petService.querpage(query);
    }
}
